package com.bd.scm.module.userSyncData.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bd.scm.dao.mapper.userSyncData.UserSyncDataMapper;
import com.bd.scm.domain.models.userSyncData.UserSyncData;
import com.bd.scm.module.userSyncData.service.UserSyncDataService;
import com.bd.scm.module.utils.httpClient.HttpClientUtil;
import com.bd.utils.DateUtils;
import com.bd.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 舍弗勒人员同步ServiceImpl
 *
 * @author YH
 * @version 1.0
 * @date 2020/10/13 13:19
 */
@Service
public class UserSyncDataServiceImpl implements UserSyncDataService {

    @Autowired
    private UserSyncDataMapper userSyncDataMapper;

    //应用ID
    @Value("${bd.appId}")
    private String appId;

    //应用密钥
    @Value("${bd.appSecret}")
    private String appSecret;

    //获取应用的AccessToken GET请求
    @Value("${bd.accessTokenURL}")
    private String accessTokenURL;

    //查询用户变更日志 GET请求
    @Value("${bd.changeLogURL}")
    private String changeLogURL;

    //通过多个雇员编号查询人员 POST请求
    @Value("${bd.personNumbersURL}")
    private String personNumbersURL;

    /**
     * 同步人员
     *
     * @return
     */
    @Override
    @Transactional
    public synchronized String datasync() throws UnknownHostException {
        String rt = null;
        String token = null;
        Map<String, Object> param = new HashMap<String, Object>();
        String currentDateSimple = DateUtils.getCurrentDateSimple();
        //添加
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSS");
        Calendar calendar = Calendar.getInstance();
        String bh = df.format(calendar.getTime()).substring(0, 16);
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        calendar.set(Calendar.HOUR_OF_DAY, -24);
        String yesterdayDate = dateFormat.format(calendar.getTime());
        //添加参数信息
        param.put("appId", appId);
        param.put("appSecret", appSecret);
        //1.获取应用的AccessToken GET请求
        JSONObject accessToken = HttpClientUtil.httpGetWithJSON(accessTokenURL, "", param);
        token = accessToken.getJSONObject("data").getString("access_token");
        //判断是否执行下一步
        if ("1".equals(accessToken.getString("code"))) {
            //2.查询用户变更日志 GET请求
            JSONObject changeLog = HttpClientUtil.httpGetWithJSON(changeLogURL + "/" + yesterdayDate + "/" + yesterdayDate, token, null);
            //判断是否执行下一步
            if ("1".equals(changeLog.getString("code"))) {
                String data = changeLog.getString("data");
                //判断日志是否为空
                if (!StringUtils.isEmpty(data)) {
                    //字符串转换JSONArray
                    JSONArray jsonArray = JSONArray.parseArray(data);
                    if (jsonArray.size() > 0) {
                        //删除集合
                        List<String> userList = new ArrayList<>();
                        //定义数组字符串
                        String arrString = "";
                        System.out.println("<<<==============================4 (" + jsonArray.size() + ")==============================>>>");
                        //遍历JSONArray DELETE UPDATE INSERT
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject arrayJSONObject = jsonArray.getJSONObject(i);
                            if ("DELETE".equals(arrayJSONObject.getString("operator"))) {
                                userList.add(arrayJSONObject.getString("personNumber"));
                            }
                            String personNumber = arrayJSONObject.getString("personNumber");
                            //装雇员编号
                            arrString += personNumber + ",";
                            if ((i % 99 == 0 && i != 0) || i == (jsonArray.size() - 1)) {
                                String[] arr = arrString.substring(0, arrString.length() - 1).split(",");
                                //3.通过多个雇员编号查询人员 POST请求
                                JSONObject personNumbers = HttpClientUtil.httpPostWithJSON(personNumbersURL, token, JSON.toJSONString(arr));
                                //判断是否成功
                                if ("1".equals(personNumbers.getString("code"))) {
                                    List<UserSyncData> userSyncDataList = JSON.parseArray(personNumbers.getString("data"), UserSyncData.class);
                                    System.out.println("<<<============================== 5: " + userSyncDataList.size() + " ==============================>>>");
                                    if (userSyncDataList.size() > 0) {
                                        //1.添加数据到临时表中
                                        this.userSyncDataMapper.insertBdEhrUserData(userSyncDataList);
                                    }
                                }
                                //数组字符串清空
                                arrString = "";
                            }
                        }
                        //修改在职状态
                        if (userList.size() > 0) {
                            String userNos = StringUtils.join(userList, ",");
                            this.userSyncDataMapper.updateEhrUserData(userNos);
                        }
                        //2.同步人员新建临时表
                        String tableName = "syn_user_" + bh;
                        this.userSyncDataMapper.createLsTableBySyn(tableName);
                        String clientIp = InetAddress.getLocalHost().getHostAddress();
                        JSONObject user = new JSONObject();
                        user.put("logIp", clientIp);
                        user.put("tableName", tableName);
                        //3.同步将数据添加到临时表
                        this.userSyncDataMapper.addSynchronizationLinShi(user);
                        //4.同步存储过程
                        this.userSyncDataMapper.execSynUser(user);
                        //5.修改临时表是否同步字段
                        this.userSyncDataMapper.updateBdEhrUserData();
                    }
                }
            }
        }
        return rt;
    }

}
